package com.gogant.spider.core;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

class ConcurrentList<T> {
	private List<T> list = new ArrayList<T>();
	private T[] array;

	public void add(T handler) {
		synchronized (list) {
			list.add(handler);
			array = null;
		}
	}

	public boolean remove(T handler) {
		synchronized (list) {
			if (list.remove(handler)) {
				array = null;
				return true;
			} else {
				return false;
			}
		}
	}

	public boolean contains(T handler) {
		synchronized (list) {
			return list.contains(handler);
		}
	}

	public int count() {
		return list.size();
	}

	public List<T> getList() {
		synchronized (list) {
			return new ArrayList<T>(list);
		}
	}

	@SuppressWarnings("unchecked")
	protected T[] getArray(Class<?> type) {
		if (this.array == null) {
			synchronized (list) {
				T[] newArray = (T[]) Array.newInstance(type, list.size());
				this.array = list.toArray(newArray);
			}
		}
		return this.array;
	}
}
